let gameInfo = {
    roomId: null,
    userId1: null,
    userId2: null,
    isBlack: true,
}

//////////////////////////////////////////////////
// 设定界面显示相关操作
//////////////////////////////////////////////////

function setScreenText(me) {
    console.log(me);
    let screen = document.querySelector('#screen');
    if (me) {
        screen.innerHTML = "轮到你落子了!";
    } else {
        screen.innerHTML = "轮到对方落子了!";
    }
}

//////////////////////////////////////////////////
// 初始化 websocket
//////////////////////////////////////////////////

let webSocket = new WebSocket('ws://127.0.0.1:8080/game');
webSocket.onopen = function() {
    console.log("连接game成功");
}
webSocket.onclose = function() {
    console.log("连接关闭请重新登陆");
}
webSocket.onerror = function() {
    console.log("error");
}

//页面关闭时释放webSocket
window.onbeforeunload = function() {
    webSocket.close();
}

//处理服务器发送的消息
webSocket.onmessage = function(e) {
    //连接成功处理返回响应
    let resp = JSON.parse(e.data);
    console.log(resp);
    if(!resp.ok) {
        alert("进入游戏房间失败: " + resp.errMsg);
        location.replace("/hall.html");
        return;
    }
    if (resp.message == 'gameReady') {
        gameInfo.roomId = resp.roomId;
        gameInfo.userId1 = resp.userId1;
        gameInfo.userId2 = resp.userId2;
        gameInfo.isBlack = resp.black;
        //初始化棋盘
        initGame();
        console.log(gameInfo);
        //提示先手玩家落子
        setScreenText(resp.black);
    } else if (resp.message == 'repeat_login') {
        alert("该账号已在别处登录");
        location.replace("/login.html");
    } else if (resp.message == 'no_login') {
        alert("当前还未登录");
        location.replace("/login.html");
    } else {
        alert("非法响应 errMsg:" + resp.errMsg);
    }  
}
//////////////////////////////////////////////////
// 初始化一局游戏
//////////////////////////////////////////////////
function initGame() {
    // 是我下还是对方下. 根据服务器分配的先后手情况决定
    let me = gameInfo.isBlack;
    // 游戏是否结束
    let over = false;
    let chessBoard = [];
    //初始化chessBord数组(表示棋盘的数组)
    for (let i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }
    let chess = document.querySelector('#chess');
    let context = chess.getContext('2d');
    context.strokeStyle = "#BFBFBF";
    // 背景图片
    let logo = new Image();
    logo.src = "image/board.png";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
    }

    // 绘制棋盘网格
    function initChessBoard() {
        for (let i = 0; i < 15; i++) {
            context.moveTo(15 + i * 30, 15);
            context.lineTo(15 + i * 30, 430);
            context.stroke();
            context.moveTo(15, 15 + i * 30);
            context.lineTo(435, 15 + i * 30);
            context.stroke();
        }
    }

    // 绘制一个棋子, me 为 true
    function oneStep(i, j, isBlack) {
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        if (!isBlack) {
            gradient.addColorStop(0, "#D1D1D1");
            gradient.addColorStop(1, "#F9F9F9");
        } else {
            gradient.addColorStop(0, "#0A0A0A");
            gradient.addColorStop(1, "#636766");
        }
        context.fillStyle = gradient;
        context.fill();
    }

    chess.onclick = function (e) {
        if (over) {
            return;
        }
        if (!me) {
            return;
        }
        let x = e.offsetX;
        let y = e.offsetY;
        // 注意, 横坐标是列, 纵坐标是行
        let col = Math.floor(x / 30);
        let row = Math.floor(y / 30);
        if (chessBoard[row][col] == 0) {
            // TODO 发送坐标给服务器, 服务器要返回结果
            webSocket.send(JSON.stringify({
                message: 'putChess',
                userId: gameInfo.userId1,
                row: row,
                col: col
            }));
            oneStep(col, row, gameInfo.isBlack);
            chessBoard[row][col] = 1;
        }
    }
    webSocket.onmessage = function (e) {
        let resp = JSON.parse(e.data);
        console.log(resp);
        if (resp.message != 'putChess') {
            console.log("响应类型错误");
            return;
        }
        //判断是谁落子
        if (resp.userId == gameInfo.userId1) {
            //根据对应棋子颜色绘制棋子
            oneStep(resp.col, resp.row, gameInfo.isBlack);
        } else if (resp.userId == gameInfo.userId2) {
            //根据对应棋子颜色绘制棋子
            oneStep(resp.col, resp.row, !gameInfo.isBlack);
        } else {
            console.log("响应出错 userId:" + resp.userId);
            return;
        }
        // 给对应的位置设置为1，表示有子
        if(resp.row != -1 && resp.col != -1) {
            chessBoard[resp.row][resp.col] = 1;
        }
        
        //交互落子方
        me = !me;
        setScreenText(me);
        //判断游戏是否结束
        if(resp.winnerId != -1) {
            let screenDiv = document.querySelector('#screen');
            if (resp.winnerId == gameInfo.userId1) {
                over = true;
                // alert("你赢了！！！");
                screenDiv.innerHTML = '你赢了！！！(点击返回大厅）';
            }
            if (resp.winnerId == gameInfo.userId2) {
                over = true;
                // alert("你输了");
                screenDiv.innerHTML = '你输了(点击返回大厅）';
            }
            screenDiv.onclick = function() {
                location.replace("/hall.html");
            }
        }

    }
}


